package controller
//controller层负责接受路由请求，然后发送请求由answer层
import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	response "hepan1/src/common/answer"
	"hepan1/src/model"
	"hepan1/src/setting"
	"hepan1/src/util"
	"math/rand"
	"net/http"
	"time"
)
//var thelasttime string = "2021-11-27-11:00:00"

// Login 登陆获取的结构体
type Login struct {
	Code string `form:"code" json:"code"`
}

// Giftinf 获奖人信息
type Giftinf struct {
	Realname string `form:"realname" json:"realname"`;
	Xuehao string `form:"xuehao" json:"xuehao"`;
	Tele string `form:"tele" json:"tele"`;
}

type Token struct {
	TheToken string `form:"token" json:"token"`
}

type wxInfor struct {
	Nickname string `form:"nickname" json:"nickname"`;
	Picurl string `form:"picurl" json:"picurl"`;
}

func GiftTime(context *gin.Context) {
	response.Success(context,0,"",map[string]interface{}{
		"stilltime":setting.Thelasttime ,
	})

}

// WXlogin1 新添加一个用户在数据表中
func WXlogin1(context *gin.Context) {
	ui := context.PostForm("code") //ui就是code
	var lo Login
	err := context.Bind(&lo)
	if util.Check(err){
		fmt.Println("有错误")
	}
	fmt.Println(lo.Code)
	ui = lo.Code
	fmt.Println("获得的code为",ui)
	errcode,errmsg ,uid :=  util.HttpDo(ui)
	fmt.Println(uid)
	if errcode!=0{
		m := map[string]interface{}{"errcode": 1, "errmsg": errmsg, "data": map[string]interface{}{}}
		context.JSON(http.StatusOK, m)
		return
	}
	var users model.Drawusers
	users.Chou = 1
	users.Openid = uid
	//_, err = model.Db.Exec("INSERT drawusers (openid,chou) values (?,1)", uid)
	err = model.Db.Create(&users).Error
	context.SetCookie("choujiang_name", uid, 3600, "/", "starstudio.uestc.edu.cn", false, false)
	if util.Check(err) {
		response.Success(context,0,"已经加入过了此用户,直接登录",nil)
		return
	}
	response.Success(context,0,"",nil)
}


// GetTheFra 抽取碎片
func GetTheFra(context *gin.Context){
	uid, _ := context.Cookie("choujiang_name")
	//defer db.Close()
	fmt.Println(uid)
	times,_ := model.Howmuchchou(uid)
	fmt.Println("执行到这")
	if times <= 0 {
		response.Fail(context,1,"此用户的抽奖次数不足")
	} else {
		fra,err := model.ChouFra(uid,times)
		if err==nil{
			data := map[string]interface{}{"fragment":fra}
			fmt.Println("data是")
			fmt.Println(data)
			fmt.Println("上面")
			response.Success(context,0,"",data)
		}else{
			response.Fail(context,1,err.Error())
		}
	}
}

// GetMyFra 查看自己的碎片
func GetMyFra(context *gin.Context){
	fmt.Println("查看碎片不了嘛")
	uid, _ := context.Cookie("choujiang_name")
	fmt.Println(uid)
	var fra = make([]int,9)
	fra,err := model.Getmyfra(uid)
	if util.Check(err){

		response.Fail(context,1,"没有此用户")
		return
	}
	fmt.Println(fra)
	m := map[string]interface{}{"sui":fra}
	response.Success(context,0,"",m)
}

// ChouTimes 获得抽奖次数
func ChouTimes(context *gin.Context){
	uid, _ := context.Cookie("choujiang_name")
	fmt.Println(uid)
	times,err := model.Choutimes(uid)
	if util.Check(err){
		response.Fail(context,0,err.Error())
		return
	}
	m := map[string]interface{}{"time":times}
	response.Success(context,0,"",m)
}

//返回自己中几等奖
func how(context *gin.Context) int {
	uid, _ := context.Cookie("choujiang_name")
	fmt.Println(uid)
	giftt,err := model.How(uid)
	//sql := fmt.Sprintf("SELECT thing FROM `luckydogs` where SID = '%s'", uid)
	//fmt.Println(sql)
	//row := db.QueryRow(sql)
	//var giftt int
	//row.Scan(&giftt)
	//if giftt == 0 {
	//	fmt.Println("您没有抽到礼物")
	//} else {
	//	fmt.Println("你的礼物是", giftt)
	//}
	if util.Check(err){
		return 0
	}
	return giftt
}

// Gift 查询用户(自己)是否抽到奖，告诉抽到几等奖。还有抽到123等奖的信息
func Gift(context * gin.Context){
	giftt := how(context)
	data,_ := model.HowPrice()
	m := map[string]interface{}{
			"myAward": giftt,
			"awardList": data,
		}

	//context.JSON(200, m)
	response.Success(context,0,"",m)
}

// GiftInform 将个人信息上传到获奖人的数据库(我是中奖人)
func GiftInform(context *gin.Context) {
	giftt := how(context)
	if giftt==0{
		m := map[string]interface{}{"errcode": 1, "errmsg":"没有获奖","data": map[string]interface{}{}}
		context.JSON(http.StatusLocked, m)
		return
	}
	var giftinfor Giftinf
	err := context.Bind(&giftinfor)
	if util.Check(err){
		fmt.Println("GiftInform有错误")
		fmt.Println(err)
	}
	realname := giftinfor.Realname    //context.PostForm("realname")
	xuehao := giftinfor.Xuehao //context.PostForm("xuehao")
	tele := giftinfor.Tele //context.PostForm("tele")
	uid, _ := context.Cookie("choujiang_name")
	//首先要判断一个人是否已经存在，存在则更新（不用）
	//sql := fmt.Sprintf("select")
	var dogsinfo model.Dogsinfor
	dogsinfo.Sid = uid
	dogsinfo.Thing = giftt
	dogsinfo.Realname = realname
	dogsinfo.Xuehao = xuehao
	dogsinfo.Tele = tele
	err = model.Db.Create(&dogsinfo).Error
	//sql := fmt.Sprintf("INSERT into  dogsinfor (SID,thing,realname,xuehao,tele) VALUES('%s',%d,'%s','%s','%s')", uid, giftt, realname, xuehao, tele)
	//fmt.Println(sql)
	//_, err = db.Exec(sql)
	//err = model.Exec(sql)
	if util.Check(err){
		response.Fail(context,1,"无法添加")
		return
	}
	response.Success(context,0,"",nil)
	//m := map[string]interface{}{"errcode": 0, "data": map[string]interface{}{}}
	//context.JSON(200, m)
}

// GiftRe 获奖人重新更新到数据库(我是中奖人)
func GiftRe(context *gin.Context) {
	var giftinfor Giftinf
	err := context.Bind(&giftinfor)
	if util.Check(err){
		fmt.Println("GiftRe有错误")
		fmt.Println(err)
	}
	realname := giftinfor.Realname    //context.PostForm("realname")
	xuehao := giftinfor.Xuehao //context.PostForm("xuehao")
	tele := giftinfor.Tele //context.PostForm("tele")
	uid, _ := context.Cookie("choujiang_name")
	//首先要判断一个人是否已经存在，存在则更新（不用）
	//sql := fmt.Sprintf("select")
	var dogsinfo model.Dogsinfor
	err = model.Db.Model(&dogsinfo).Where("sid = ?",uid).Update(map[string]interface{}{"realname":realname, "xuehao":xuehao, "tele":tele}).Error
	//sql := fmt.Sprintf("update dogsinfor set realname='%s' , xuehao='%s',tele='%s' where SID='%s'", realname, xuehao, tele, uid)
	//err = model.Exec(sql)
	if util.Check(err){
		response.Fail(context,1,"无法添加")
		return
	}
	//fmt.Println(sql)
	response.Success(context,0,"",nil)
}

// GetTheTimes 前端通过调用接口来让用户获得一次的抽奖机会
func GetTheTimes(context *gin.Context) {
	var to Token
	err := context.Bind(&to)
	//to.TheToken = context.PostForm("token")
	if util.Check(err){
		fmt.Println("GetTheTimes有错误")
		fmt.Println(err)
	}
	token := to.TheToken
	uid, _ := context.Cookie("choujiang_name")
	fmt.Println("openid为",uid)
	//var toke model.Choujiangtokens
	fmt.Println("获取到的token为",token)
	//mm := model.Db.Unscoped().Where("tokens = ?",token).Delete(&toke)

	affect,err := model.RedisDb.LRem("choujiangtokens",1,token).Result()
	//err = mm.Error
	//affect := mm.RowsAffected
	//stm := fmt.Sprintf("delete from choujiangtokens where tokens ='%s'", token)
	//fmt.Println(stm)
	//fmt.Println("获得机会到这里")
	//affect,err := model.Exec2(stm)
	if util.Check(err){
		response.Fail(context,1,err.Error())
	}
	fmt.Println(affect)
	var can int // 是否允许抽奖
	if affect >= 1 {
		can = 1
		//stm = fmt.Sprintf("update drawusers set chou=chou+1 WHERE openid = '%s'", uid)
		var user model.Drawusers
		err = model.Db.Model(&user).Where("openid = ?",uid).Update("chou", gorm.Expr("chou+1")).Error
		//err = model.Exec(stm)
		util.Check(err)
	}
	m := map[string]interface{}{
		"can": can,
	}
	response.Success(context,0,"",m)
}

// ComeToDraw 前端通过调用接口来让用户抽奖(用户需要有9个碎片才可以抽奖)
func ComeToDraw(context *gin.Context){
	uid, _ := context.Cookie("choujiang_name")
	var wxinfor wxInfor
	err := context.Bind(&wxinfor)
	if util.Check(err){
		fmt.Println("ComeToDraw有问题")
		response.Fail(context,1,err.Error())
		return
	}
	fmt.Println(uid)
	var user model.Drawusers
	affect := model.Db.Where("sui1>=1 and sui2>=1 and sui3>=1 and sui4>=1 and sui5>=1 and sui6>=1 and sui7>=1 and sui8>=1 and sui9>=1 and openid=?",uid).First(&user).RowsAffected
	//stm := fmt.Sprintf("SELECT openid FROM `drawusers` where sui1>=1 and sui2>=1 and sui3>=1 and sui4>=1 and sui5>=1 and sui6>=1 and sui7>=1 and sui8>=1 and sui9>=1 and openid='%s'",uid)
	//fmt.Println(stm)
	//valid := model.QueryRow(stm)
	if affect<=0{
		response.Fail(context,1,"碎片不足")
		return
	}
	mm := model.Db.Model(&user).Where("openid = ? and nickname is NULL",uid).Update(map[string]interface{}{"nickname":wxinfor.Nickname,"picture":wxinfor.Picurl})
	affect = mm.RowsAffected
	err = mm.Error
	//stm = fmt.Sprintf("UPDATE drawusers set nickname='%s',picture='%s' where openid='%s' and nickname is NULL",wxinfor.Nickname,wxinfor.Picurl,uid)
	//fmt.Println(stm)
	//affect,err := model.Exec2(stm)
	if util.Check(err) || affect==0{
		fmt.Println(err)
		response.Fail(context,1,"已经抽过")
		return
	}
	var candidatedog model.Candidatedogs
	candidatedog.Sid = uid
	candidatedog.Nickname = wxinfor.Nickname
	candidatedog.Picture = wxinfor.Picurl
	err = model.Db.Create(&candidatedog).Error
	//stm = fmt.Sprintf("insert into candidatedogs (SID,nickname,picture) values ('%s','%s','%s')",uid,wxinfor.Nickname,wxinfor.Picurl)
	//fmt.Println(stm)
	//err = model.Exec(stm)
	if util.Check(err){
		response.Fail(context,1,"已经抽过")
		return
	}
	m := map[string]interface{}{
		"can": 0,
	}
	response.Success(context,0,"",m)
}

// EverDraw 查看目前用户是否抽奖过
func EverDraw(context *gin.Context){
	uid, _ := context.Cookie("choujiang_name")
	var user model.Drawusers
	affect := model.Db.Where("openid = ? and nickname is not NULL", uid).First(&user).RowsAffected
	//stm := fmt.Sprintf("select openid from drawusers where openid='%s' and nickname is not NULL",uid)
	//var has string
	//valid := db.QueryRow(stm).Scan(&has)
	//valid := model.QueryRow(stm)
	//affect,_ := res.RowsAffected()
	var can int //返回0则说明可以抽奖，返回1则说明不允许抽奖
	if affect > 0 {
		can=1
	}
	m := map[string]interface{}{"errcode": 0, "data": map[string]interface{}{
		"can": can,
	}}
	context.JSON(200,m)
}

// GiftQRcode 返回一个二维码所包含的信息,用户扫描这个二维码来获得抽奖机会
func GiftQRcode(context *gin.Context) {
	var xiaogift int
	rand.Seed(time.Now().UnixNano())
	if rand.Intn(100) < 50 {
		xiaogift = 1
	}
	token := util.GetRandomString(32)
	fmt.Println(token)
	//setKey := "choujiangtokens"
	//SADD
	//var toke model.Choujiangtokens
	//toke.Tokens = token
	//err := model.Db.Create(&toke).Error

	err := model.RedisDb.RPush( "choujiangtokens", token ).Err()
	//stm := fmt.Sprintf("insert INTO choujiangtokens (tokens) VALUES('%s')", token)
	//_, err := db.Exec(stm)
	//err := model.Exec(stm)
	if util.Check(err) {
		response.Fail(context,1,"无法获取二维码信息")
		//m := map[string]interface{}{"errcode": 1, "errmsg": "无法获取二维码信息", "data": map[string]interface{}{}}
		//context.JSON(200, m)
		return
	}
	fmt.Println(xiaogift)
	m := map[string]interface{}{"errcode": 0, "data": map[string]interface{}{
		"token": token,
		"gift":  xiaogift,
	}}
	context.JSON(200, m)
}